package com.yndsoft.jc.supplier.widget.recyclerview;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RecyclerHolder extends RecyclerView.ViewHolder {

    public View mConvertView;
    public int position;
    private SparseArray<View> mViews;

    public RecyclerHolder(View itemView) {
        super(itemView);
        this.mConvertView = itemView;
        this.mViews = new SparseArray<>();
        mConvertView.setTag(this);
    }

    public static RecyclerHolder getHolder(Context context, ViewGroup parent, int layoutId) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(layoutId, parent, false);
        RecyclerHolder recyclerHolder = new RecyclerHolder(itemView);
        return recyclerHolder;
    }

    public <T extends View> T findViewById(@IdRes int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public RecyclerHolder setTvText(@IdRes int resId, String text) {
        setTvText((TextView) findViewById(resId), text);
        return this;
    }

    public RecyclerHolder setTvText(TextView tv, String text) {
        tv.setText(!TextUtils.isEmpty(text) ? text : "");
        return this;
    }

    public RecyclerHolder setOnClickListener(RecyclerListener.OnClickListener clickListener, @IdRes int... viewIds) {
        RecyclerListener listener = new RecyclerListener(position, this);
        listener.setOnClickListener(clickListener);
        for (int id : viewIds) {
            View v = findViewById(id);
            v.setOnClickListener(listener);
        }
        return this;
    }

    public RecyclerHolder setOnLongClickListener(RecyclerListener.OnLongClickListener longClickListener, @IdRes int... viewIds) {
        RecyclerListener listener = new RecyclerListener(position, this);
        listener.setOnLongClickListener(longClickListener);
        for (int id : viewIds) {
            View v = findViewById(id);
            v.setOnLongClickListener(listener);
        }
        return this;
    }
}
